package com.sikong.calcite.csv;

import com.google.common.collect.ImmutableMap;
import com.sikong.constant.StringSpliter;
import lombok.extern.slf4j.Slf4j;
import org.apache.calcite.schema.Table;
import org.apache.calcite.schema.impl.AbstractSchema;

import java.io.FileReader;
import java.util.Map;
import java.util.Objects;

/**
 * 自定义CsvSchema
 *
 * @author wangbohong
 * @date 2022/03/09 16:26:22
 * @since 0.1.0
 */
@Slf4j
public class CsvSchemaDemo extends AbstractSchema {

    private String dataFile;

    public CsvSchemaDemo(String dataFile) {
        this.dataFile = dataFile;
    }

    @Override
    protected Map<String, Table> getTableMap() {
        try {
            final ImmutableMap.Builder<String, Table> builder = ImmutableMap.builder();
            for (String df : dataFile.split(StringSpliter.COMMA)) {
                FileReader reader = new FileReader(
                        Objects.requireNonNull(this.getClass().getClassLoader().getResource(df)).getFile());
                builder.put(df.split(StringSpliter.DOTE)[0], new CsvTableDemo(reader));
            }
            return builder.build();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
